package com.threegroup.web.service;

import com.alibaba.fastjson.JSON;
import com.threegroup.common.exception.TakeOutException;
import com.threegroup.common.utils.Result;
import com.threegroup.web.dao.CategoryEntityMapper;
import com.threegroup.web.pojo.CategoryEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class CategoryForGuestService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CategoryEntityMapper categoryEntityMapper;

    public static Long TIME_OUT_CACHE = 1L;

    /**
     * 获取categoryList
     * @return
     */
    public Result<List<CategoryEntity>> getCategoryList() {
        //准备结果集
        Result<List<CategoryEntity>> listResult = new Result<>();
        /**
         * 准备redis模板
         */
        HashOperations<String, String, String> opsForHash = stringRedisTemplate.opsForHash();
        stringRedisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        //查询redis是否存在该信息
        List<CategoryEntity> entityList;
         String s = opsForHash.get("CategoryEntityList", "list");
         if (!StringUtils.isBlank(s)){
             //有数据就转型并返回
             entityList = JSON.parseArray(s,CategoryEntity.class);
             if (entityList!=null&&entityList.size()!=0){
                 //把保存时间重置
                 stringRedisTemplate.expire("CategoryEntityList",TIME_OUT_CACHE, TimeUnit.SECONDS);//设置失效时间一天
                 //如果查到的Redis里有数据，则直接返回
                 listResult.setData(entityList);
                 return listResult;
             }
         }

        //否则 查询数据库
        entityList = categoryEntityMapper.queryAll();

        if (entityList!=null&&entityList.size()!=0){
            //保存redis
            //把查到的结果转型
            String jsonString = JSON.toJSONString(entityList);
            opsForHash.put("CategoryEntityList","list",jsonString);
            stringRedisTemplate.expire("CategoryEntityList",TIME_OUT_CACHE, TimeUnit.SECONDS);//设置失效时间一天
            //返回数据
            listResult.setData(entityList);
            return listResult;
        }else {

            throw new TakeOutException(303 , "为查询到数据");

        }




    }
}
